package logic

import (
	"context"
	"errors"
	"user_srv/mysql"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealnameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealnameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealnameLogic {
	return &RealnameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RealnameLogic) Realname(in *user.RealnameRequest) (*user.RealnameResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var ur mysql.UserRealname
	ur.UserId = int(in.UserId)

	err = ur.GetUserRealnameByUserId()
	if err != nil {
		logx.Error("查询用户实名信息失败:", err)
		return nil, err
	}

	if ur.ID != 0 {
		logx.Error("用户已实名")
		return nil, errors.New("用户已实名")
	}

	//调用第三方接口进行认证
	if !pkg.RealnameAuth(in.Idcard, in.Name) {
		logx.Error("用户实名认证失败")
		return nil, errors.New("用户实名认证失败")
	}

	//保存认证信息
	ur.Realname = in.Name
	ur.IdCard = in.Idcard
	err = ur.Create()
	if err != nil {
		logx.Error("保存用户实名信息失败", err)
		return nil, err
	}

	return &user.RealnameResponse{
		Id: int64(ur.ID),
	}, nil
}
